package com.zhouyu.processor;

import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * // 通过 BeanProcessor 实现一个自定义的属性依赖注入
 * @author yangjian
 */
@Component
public class MyInstantiationAwarePostProcessor implements InstantiationAwareBeanPostProcessor {

	@Override
	public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException
	{
		if ("orderService".equals(beanName)) {
			for (Field field : bean.getClass().getDeclaredFields()) {
				if (field.isAnnotationPresent(TestInject.class)) {
					field.setAccessible(true);
					try {
						field.set(bean, field.getAnnotation(TestInject.class).value());
					} catch (IllegalAccessException e) {
						throw new RuntimeException(e);
					}
				}
			}
		}
		return pvs;
	}
}
